#include <unistd.h>
#include <pthread.h>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
#include "ringQueue.hpp"

using namespace std;

ringQueue<int>* q = new ringQueue<int>(5);

struct Thread
{
    pthread_t _th;
    string _name;
};

void* Consumer(void* args)
{
    //ringQueue<int>* q = static_cast<ringQueue<int>*>(args);
    uint64_t id = (uint64_t)args;
    //sleep(3);
    while(true)
    {
        //消费数据
        int t = q->pop();
        cout << "consumer get a task:" << t << ", id:" << id << endl;
        //处理数据
        //TODO
        sleep(1);
    }
}

void* Producer(void* args)
{
    //ringQueue<int>* q = static_cast<ringQueue<int>*>(args);
    uint64_t id = (uint64_t)args;
    // sleep(3);
    while(true)
    {
        //获取数据
        int t = rand() % 10 + 1;
        //生产数据
        q->push(t);
        cout << "producer product a task:" << t << ", id:" << id << endl;
        //sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr));
    std::vector<Thread> consumers(3);
    std::vector<Thread> producers(5);
    for (uint64_t i = 0; i < 3; ++i) {
        consumers[i]._name = "consumer-" + to_string(i);
        pthread_create(&(consumers[i]._th), nullptr, Consumer, (void*)i);
    }
    for (uint64_t i = 0; i < 5; ++i) {
        producers[i]._name = "producer-" + to_string(i);
        pthread_create(&(producers[i]._th), nullptr, Producer, (void*)i);
    }
    for (auto& th : consumers) {
        pthread_join(th._th, nullptr);
    }
    for (auto& th : producers) {
        pthread_join(th._th, nullptr);
    }

    // pthread_t c, p;
    // pthread_create(&c, nullptr, Consumer, q);
    // pthread_create(&p, nullptr, Producer, q);
    // pthread_join(c, nullptr);
    // pthread_join(p, nullptr);
    return 0;
}